package com.vsen.lpr.task;

import com.vsen.lpr.entity.TaskPlan;
import com.vsen.lpr.mapper.TaskPlanMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;

/**
 * 定时任务  从数据库中扫描放到队列中
 */

@Component
@Configuration
@EnableScheduling
public class DelayTaskPrivoder {
    @Autowired
    TaskPlanMapper taskPlanMapper;

    @Scheduled(fixedRate = 60000 )
    private void timingLoadDataFromDB(){
        Calendar now1 = Calendar.getInstance();
        now1.setTime(new java.util.Date());
        now1.add(Calendar.MINUTE, 5);
        java.util.Date afterFiveMin = now1.getTime();

        System.err.println(afterFiveMin);
        Date date = new Date(afterFiveMin.getTime());


        List<TaskPlan> taskPlans = taskPlanMapper.queryTaskByNowTime2(new Date(System.currentTimeMillis()), afterFiveMin);

        System.err.println(date);
        if (CollectionUtils.isEmpty(taskPlans)) {
            return;
        }
        for (TaskPlan taskPlan : taskPlans) {

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            long remindTime = taskPlan.getRemindTime().getTime();

            long now = System.currentTimeMillis();
            System.out.println("now"+sdf.format(new Date(now)));

            long addNow = System.currentTimeMillis() + 1000 * 60;
            System.out.println("addNow"+sdf.format(new Date(addNow)));

            long interval = taskPlan.getIntervalTime();
            long remind = remindTime;

            while (remind< now) {
                remind += interval;
            }

            while (remind>now&&remind <= addNow) {
                System.out.println("满足触发时间"+sdf.format(new Date(remind))+"丢入队列");
                TaskPlan plan = new TaskPlan();
                plan.setRemindTime(new Date(remind));
                plan.setContext(taskPlan.getContext());
                plan.setCreateTime(taskPlan.getCreateTime());
                plan.setEndTime(taskPlan.getEndTime());
                plan.setId(taskPlan.getId());
                plan.setIntervalTime(taskPlan.getIntervalTime());
                plan.setName(taskPlan.getName());
                plan.setExecuteTine(taskPlan.getExecuteTine());
                plan.setIsRemind(taskPlan.getIsRemind());
                plan.setRemindTime(new Date(remind));
                plan.setUserId(taskPlan.getUserId());
                TaskUtil.add(plan);
                remind += interval;
            }
        }
    }
}
